package com.longcai.controller.scm;


import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.longcai.bean.ApiResult;
import com.longcai.entity.homegood.ClyjGoodsSpec;
import com.longcai.entity.homepage.ClyjNearbyBanner;
import com.longcai.entity.homepage.GoodsClass;
import com.longcai.entity.scm.ClyjScmGoods;
import com.longcai.entity.scm.ClyjScmGoodsSpec;
import com.longcai.entity.scm.ClyjScmGoodsType;
import com.longcai.entity.sys.SysRoleUser;
import com.longcai.entity.sys.SysUser;
import com.longcai.service.ClyjNearbyBannerService;
import com.longcai.service.goods.GoodsClassService;
import com.longcai.service.scm.ClyjScmGoodsService;
import com.longcai.service.scm.ClyjScmGoodsSpecService;
import com.longcai.service.scm.ClyjScmGoodsTypeService;
import com.longcai.util.LoginUser;
import com.longcai.util.Token;
import com.longcai.util.UserUtil;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

/**
 * <p>
 * 供应链商品表 前端控制器
 * </p>
 *
 * @author LWK
 * @since 2019-04-24
 */
@Controller
@RequestMapping("/clyjScmGoods")
public class ClyjScmGoodsController {
	@Resource
    private ClyjScmGoodsService clyjGoodsService;
	@Resource
    private GoodsClassService goodsClassService;
	@Resource
    private ClyjNearbyBannerService bannerService;
	@Resource
    private ClyjScmGoodsTypeService clyjGoodsTypeService;
	@Resource
	private ClyjScmGoodsSpecService clyjGoodsSpecService;
	
	 /**
     * 获取供应链商品分类树
     *
     * @return
     */
	@RequestMapping(value="getGoodsClass")
    @ResponseBody
    public JSONArray getGoodsClass() {
    	QueryWrapper<GoodsClass> queryWrapper = new QueryWrapper<GoodsClass>();
    	queryWrapper.eq("type", "3");
    	queryWrapper.orderByAsc("type_sort");
    	List<GoodsClass> selectList = goodsClassService.selectList(queryWrapper);
    	JSONArray array = new JSONArray();
        setPermissionsTree("0", selectList, array);
         return array;
    }
    
    /**
     * 菜单树
     *
     * @param pId
     * @param permissionsAll
     * @param array
     */
    private void setPermissionsTree(String pId, List<GoodsClass> permissionsAll, JSONArray array) {
        permissionsAll.forEach(a -> {
            if ((pId.equals("0") && a.getPId() == null) || (a.getPId() != null && a.getPId().equals(pId))) {
                String string = JSONObject.toJSONString(a);
                JSONObject parent = (JSONObject) JSONObject.parse(string);
                array.add(parent);

                if (permissionsAll.stream().filter(p -> p.getPId() != null && p.getPId().equals(a.getId())).findAny() != null) {
                    JSONArray child = new JSONArray();
                    parent.put("child", child);
                    setPermissionsTree(a.getId(), permissionsAll, child);
                }
            }
        });
    }
    
    /**
     * 获取供应链商品活动分类
     *
     * @return
     */
    @RequestMapping(value="getActivClass")
    @ResponseBody
    public List<GoodsClass> getActivClass() {
    	
    	QueryWrapper<GoodsClass> queryWrapper = new QueryWrapper<GoodsClass>();
    	queryWrapper.eq("type", "4");
    	queryWrapper.orderByAsc("type_sort");
    	List<GoodsClass> selectList = goodsClassService.selectList(queryWrapper);
         return selectList;
    }
    /**
     * 获取供应链banner
     *
     * @return
     */
    @RequestMapping(value="getBanner")
    @ResponseBody
    public List<ClyjNearbyBanner> getBanner() {
    	QueryWrapper<ClyjNearbyBanner> queryWrapper = new QueryWrapper<ClyjNearbyBanner>();
    	queryWrapper.eq("banner_type", "2");
    	queryWrapper.orderByAsc("banner_sort");
    	List<ClyjNearbyBanner> selectList = bannerService.selectList(queryWrapper);
         return selectList;
    }
    
    /**
     * 获取商品列表
     * @param goodsId				商品id（用于查询商品详情）
     * @param goodsName				商品名称（模糊查询）
     * @param presentPrice			商品最低价格（价格筛选）
     * @param originalPrice			商品最高价（价格筛选）
     * @param goodsBrandId			商品品牌
     * @param goodsStatus			商品状态（0：正常；1：首页推荐；2：禁用或下架）
     * @param typesId				商品类型Id
     * @param sortName				排序字段
     * @param sortType				排序方式
     * @return	List<ClyjScmGoods>
     */
    @RequestMapping(value="getScmGoods")
    @ResponseBody
    public List<ClyjScmGoods> getScmGoods(ClyjScmGoods clyjScmGoods,String sortName,String sortType) {
    	//定义查询参数
    	QueryWrapper<ClyjScmGoods> queryWrapper = new QueryWrapper<ClyjScmGoods>();
    	try{
	    	//商品类型判断
	    	if(clyjScmGoods.getTypesId()!=null && !clyjScmGoods.getTypesId().equals("")){
	    		QueryWrapper<ClyjScmGoodsType> queryGoodsClass = new QueryWrapper<ClyjScmGoodsType>();
	    		queryGoodsClass.eq("type_id", clyjScmGoods.getTypesId());
	    		//商品类型中间表查询
	    		List<ClyjScmGoodsType> selectList = clyjGoodsTypeService.selectList(queryGoodsClass);
	    		if(selectList!=null && selectList.size()>0){
	    			List<String> goodsIdList = new ArrayList<String>();
		    		for (ClyjScmGoodsType clyjScmGoodsType : selectList) {
		    			goodsIdList.add(clyjScmGoodsType.getGoodsId());
					}
		    		queryWrapper.in("goods_id", goodsIdList);
	    		}
	    	}
	    	//商品id判断
	    	if(clyjScmGoods.getGoodsId()!=null && !clyjScmGoods.getGoodsId().equals("")){
	    		queryWrapper.eq("goods_id", clyjScmGoods.getGoodsId());
	    	}
	    	//商品名称判断
	    	if(clyjScmGoods.getGoodsName()!=null && !clyjScmGoods.getGoodsName().equals("")){
	    		queryWrapper.like("goods_name", clyjScmGoods.getGoodsName());
	    	}
	    	//商品状态判断
	    	if(clyjScmGoods.getGoodsStatus()!=null && !clyjScmGoods.getGoodsStatus().equals("")){
	    		String goodsStatus = clyjScmGoods.getGoodsStatus();
	    		String[] split = goodsStatus.split(",");
	    		queryWrapper.in("goods_status", split);
	    	}
	    	//商品最低价判断
	    	if(clyjScmGoods.getPresentPrice()!=null && !clyjScmGoods.getPresentPrice().equals("")){
	    		BigDecimal presentPrice = clyjScmGoods.getPresentPrice();
	    		queryWrapper.ge("present_price",presentPrice);
	    	}
	    	//商品最高价判断
	    	if(clyjScmGoods.getOriginalPrice()!=null && !clyjScmGoods.getOriginalPrice().equals("")){
	    		BigDecimal originalPrice = clyjScmGoods.getOriginalPrice();
	    		queryWrapper.le("present_price",originalPrice);
	    	}
	    	//商品品牌判断
	    	if(clyjScmGoods.getGoodsBrandId()!=null && !clyjScmGoods.getGoodsBrandId().equals("")){
	    		queryWrapper.eq("goods_brand_id",clyjScmGoods.getGoodsBrandId());
	    	}
	    	//商品排序字段
	    	if(sortType!=null && !sortType.equals("") && sortType.equals("asc")){
	    		queryWrapper.orderByAsc(sortName);
	    	}
	    	if(sortType!=null && !sortType.equals("") && sortType.equals("desc")){
	    		queryWrapper.orderByDesc(sortName);
	    	}
	    	List<ClyjScmGoods> selectList = clyjGoodsService.selectList(queryWrapper);
	    	return selectList;
    	}catch(Exception e){
    		e.printStackTrace();
    	}
        return null;
    }
    /**
     * 查询商品规格
     *
     * @param params
     * @return
     */
    @RequestMapping("/getGoodsSpec")
    @ResponseBody
    public ApiResult getGoodsSpec(@RequestBody JSONObject params) {
        String goodsid = params.getString("goodsid");
        if (StringUtils.isNotEmpty(goodsid) && !goodsid.equals("")) {
        	QueryWrapper<ClyjScmGoodsSpec> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("goods_id", goodsid);
            List<ClyjScmGoodsSpec> list = this.clyjGoodsSpecService.selectList(queryWrapper);
            return ApiResult.success(list);
        } else {
            return ApiResult.fail("商品id不能为空");
        }
    }

    /**
     * 获取规格图片
     *
     * @param params
     * @return
     */
    @RequestMapping("/getSpecPics")
    @ResponseBody
    public ApiResult getSpecPics(@RequestBody JSONObject params) {
        String id = params.getString("id");
        if (id == null || id.equals("")) {

            return ApiResult.fail("查询失败");
        }
        return this.clyjGoodsSpecService.getSpecPics(id);

    }
    /**
     * 确认购买获取商户信息
     *
     * @param params
     * @return
     */
    @RequestMapping("/getUserDetail")
    @ResponseBody
    public ApiResult getUserDetail(@RequestBody JSONObject params) {
    	LoginUser loginUser = UserUtil.getLoginUser();
        return ApiResult.success(loginUser);

    }
    
}

